package org.numb.concurrency.chapter03;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

public class FairLock {

    public static void main(String[] args) {
        System.out.println("公平锁");
        fairLock();
    }

    public static void fairLock() {
        // 公平锁
        ReentrantLock lock = new ReentrantLock(true);

        Runnable runnable = () -> {
            lock.lock();
            System.out.println(Thread.currentThread().getName() + " lock");
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            lock.unlock();
            System.out.println(Thread.currentThread().getName() + " unlock");
        };
        // 启动5个线程，按顺序依次获取锁
        for (int i = 0; i < 5; i++) {
            Thread t = new Thread(runnable);
            t.setName("thread-" + i);
            t.start();
        }
    }

    public static void noFairLock() {
        // 非公平锁
        ReentrantLock lock = new ReentrantLock(false);

        Runnable runnable = () -> {
            lock.lock();
            System.out.println(Thread.currentThread().getName() + " lock");
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            lock.unlock();
            System.out.println(Thread.currentThread().getName() + " unlock");
        };
        // 启动5个线程，随机获取锁
        for (int i = 0; i < 5; i++) {
            Thread t = new Thread(runnable);
            t.setName("thread-" + i);
            t.start();
        }
    }

}
